<script>
export default {
  name: "LsdTable",
  props: {
    options: {
      type: Object,
      default: () => ({})
    },
    compRef: {
      type: String,
      default: "customTable"
    },
    // 表格左边label
    formLabel: {
      type: Object
    },
    tableAttr: {
      type: Object,
      default: () => {
        return {
          height: "100%",
          stripe: false,
          border: true,
          fit: true,
          "show-header": true,
          "highlight-current-row": true,
          size: "small",
          "cell-style": {
            "font-size": "14px"
          },
          "header-cell-style": {
            "text-align": "center",
            "background-color": "#B1C8F9",
            "font-size": "14px"
          }
        };
      }
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    autoHeight: {
      type: Boolean
    },
    // 是否显示多选列
    isSelectFlag: {
      type: Boolean,
      default: false
    },
    selectColumnAttr: {
      type: Object,
      default: () => {}
    },
    // 表格标题
    title: {
      type: String,
      default: ""
    },
    // 是否显示序号列
    isSequenceFlag: {
      type: Boolean,
      default: false
    },
    // 是否显示分页
    isShowPage: {
      type: Boolean,
      default: false
    },
    // 表单数据
    tableData: {
      type: Array,
      default: () => []
    },
    // 表格左上角按钮
    actions: {
      type: Array,
      default: () => []
    },
    // 需要展示的表单数据项
    columns: {
      type: Array,
      default: () => []
    },
    paginationAtrrs: {
      type: Object,
      default: () => {
        return {
          total: 0,
          "background": true,
          layout: "prev, pager, next",
          "current-page": 1,
          "page-size": 10
        };
      }
    },
    // 通过在父组件改变值，从而重置选择
    resetFlag: {
      type: Boolean,
      default: false
    },
    // 遮罩层
    loading: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      key: Math.random(),
      selection: [],
      height: `${window.innerHeight - 512}px`,
      paginationAtrrsInner: {
        total: this.paginationAtrrs.total,
        "background": true,
        layout: "prev, pager, next",
        "current-page": 1,
        "page-size": 10
      }
    };
  },
  computed: {
    heightAttr() {
      const bodyHeight = document.body.offsetHeight;
      const tableHeight = bodyHeight - (bodyHeight * 55 / 100) + "px";
      return this.autoHeight ? { height: null } : { height: this.tableAttr.height ? this.tableAttr.height : tableHeight };
    },
    nowPower() {
      // const result = this.$store.state.nowPowerList.component.replaceAll("、", ",");
      // return JSON.parse(`[${result}]`);
      return this.$store.state.nowPowerList;
    }
  },
  watch: {
    resetFlag() {
      this.resetSelection();
    },
    tableData: {
      handler() {
        this.$nextTick(() => {
          this.$refs[this.compRef].doLayout();
          this.height = `${window.innerHeight - 512}px`;
        });
      },
      deep: true
    },
    paginationAtrrs: {
      handler(val) {
        this.paginationAtrrsInner.total = val.total;
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.checkF11();
    // F11事件
    window.onresize = () => {
      this.height = `${window.innerHeight - 512}px`;
    };
  },
  methods: {
    cheIsHasPower(item) {
      // const powerobj = {
      //   "daochu": "导出"
      // };
      if (item.isPower) {
        if (this.nowPower) {
          const nowList = this.nowPower.find(i => i.btnName === item.text) || {};
          if (nowList.id) {
            return true;
          } else {
            return false;
          }
        } else {
          return false;
        }
      } else {
        if (item.isShow) {
          return true;
        } else {
          const { roleCode } = JSON.parse(sessionStorage.getItem("role"));
          const roleList = roleCode.split(",");
          const hasPowerList = ["hb_sys", "hb_tbr", "operator_leader", "operator_director", "system"];
          const setRoleList = new Set(roleList);
          const setHasPowerList = new Set(hasPowerList);
          const falg = [...setRoleList].some((i) => setHasPowerList.has(i));
          if (!["导出"].includes(item.text) && !falg) {
            return false;
          } else {
            return item.show !== undefined ? item.show : true;
          }
        }
      }
    },
    checkF11() {
      this.height = `${window.innerHeight - 512}px`;
    },
    // 取消回显
    cancelSelect(val) {
      this.tableData.forEach((row) => {
        if (row.id === val) {
          this.$refs[this.compRef].toggleRowSelection(row, false);
        }
      });

    },
    // 表格回显
    toggleSelection(rows) {
      if (rows) {
        this.tableData.forEach((row) => {
          rows.forEach(item => {
            if (row.id === item) { this.$refs[this.compRef].toggleRowSelection(row, true); }
          });
        });
      } else {
        this.$refs[this.compRef].clearSelection();
      }
    },
    // 计算分页页数
    calcNum(val) {
      if (val < 10) {
        return 1;
      } else {
        return Math.ceil(val / 10);
      }
    },
    // 重置选择
    resetSelection() {
      this.$refs[this.compRef].clearSelection();
    },
    indexMethod(index) {
      return (
        (this.paginationAtrrs["current-page"] - 1) *
        this.paginationAtrrs["page-size"] +
        1 +
        index
      );
    },
    handleSizeChange(val) {
      this.paginationAtrrsInner["page-size"] = val;
      this.$emit("pageChange", { "page-size": val, "current-page": 1 });
    },
    handleCurrentChange(val) {
      this.paginationAtrrsInner["current-page"] = val;

      this.$emit("pageChange", {
        "page-size": this.paginationAtrrs["page-size"],
        "current-page": val
      });
    },
    tableCellTextButClick(row, item) {
      this.$emit("tableCellTextButClick", row, item);
    },
    isSequenceFlagMeth() {
      if (this.isSequenceFlag && this.columns.length > 0) {
        return (
          <el-table-column
            fixed
            align='center'
            label='序号'
            type='index'
            index={this.indexMethod}
            width='60'
          />
        );
      }
    },
    isSelectFlagMeth() {
      if (this.isSelectFlag && this.columns.length > 0) {
        return (
          <el-table-column
            fixed
            align='center'
            type='selection'
            width='50'
            {...{ attrs: this.selectColumnAttr }}
          />
        );
      }
    },
    // 分页
    generatePage() {
      if (this.isShowPage) {
        return (
          <div style='display:flex;justify-content: flex-end;align-items: center;font-size:16px;margin-top:10px'>
            <div style='letter-spacing: 2px;margin-right:2px'>共{this.paginationAtrrs.total}条数据,共{this.calcNum(this.paginationAtrrs.total)}页</div>
            <el-pagination
              onSize-change={this.handleSizeChange}
              onCurrent-change={this.handleCurrentChange}
              {...{
                attrs: this.paginationAtrrsInner
              }}
              style={
                "display: flex;justify-content: flex-end;overflow: auto;margin-top:5px"
              }
            ></el-pagination>
          </div>
        );
      }
    }
  },
  render(h) {
    const self = this;
    return (
      <div style='text-align: center;display:flex;flex-direction:column'>
        {this.title && this.title !== "" && (
          <div class='title'>{this.title}</div>
        )}
        {
          (
            <div style={{ display: this.actions.length > 0 ? "block" : "none" }}>
              <ul class='leftTopBtn'>
                {
                  (this.actions && this.actions.length > 0) &&
                  this.actions.map((item, index) => {
                    return (
                      <li key={"btn_" + index} v-show={JSON.stringify(item) !== "{}"}>.
                        <el-button
                          // style="font-size:16px"
                          v-show={this.cheIsHasPower(item)}
                          type={item.type}
                          {...{
                            on: {
                              click: () => {
                                this.$emit("onActionClick", item, index);
                              }
                            },
                            attrs: {
                              ...item.btnAttr
                            }
                          }}
                        >
                          {item.text}
                        </el-button>
                      </li>
                    );
                  })}
              </ul>
            </div>
          )
        }
        <div style={{ display: this.formLabel ? "flex" : "block" }}>
          {this.formLabel && (
            <div style='height:55px;display:flex;align-item:center;'>
              {
                this.formLabel.prompt &&
                <div style='color:#F56C6C;margin-right: 4px;font-size:28px;margin: -5px -5px 0 0;'>*</div>
              }
              <div class='formLabel' style={{ width: this.formLabel.width ? this.formLabel.width : "113px" }}>{this.formLabel.label}</div>
            </div>
          )
          }
          < div style='flex:1;' >
            <el-table
              ref={this.compRef}
              v-loading={this.loading}
              {...{
                attrs: {
                  ...this.tableAttr,
                  ...this.heightAttr,
                  data: this.tableData,
                  key: this.key
                },
                on: {
                  select: (selection, row) => {
                    const multipleSelection = [];
                    if (!this.multiple) {
                      if (selection.length > 1) {
                        const del_row = selection.shift();
                        this.$refs[this.compRef].toggleRowSelection(del_row, false);
                      }
                      multipleSelection.push(selection[0]);
                    }
                    this.selection = this.multiple ? selection : multipleSelection;
                    this.$emit("select", this.selection, row);
                  },
                  "select-all": (selection) => {
                    this.selection = selection;
                    this.$emit("select-all", this.selection);
                  },
                  "selection-change": (selection) => {
                    this.selection = selection;
                    this.$emit("selection-change", this.selection);
                  },
                  "cell-mouse-enter": (row, column, cell, event) => {
                    this.$emit("cell-mouse-enter", row, column, cell, event);
                  },
                  "cell-mouse-leave": (row, column, cell, event) => {
                    this.$emit("cell-mouse-leave", row, column, cell, event);
                  },
                  "cell-click": (row, column, cell, event) => {
                    this.$emit("cell-click", row, column, cell, event);
                  },
                  "cell-dblclick": (row, column, cell, event) => {
                    this.$emit("cell-dblclick", row, column, cell, event);
                  },
                  "row-click": (row, column, event) => {
                    this.$emit("row-click", row, column, event);
                    if (this.isSelectFlag) { this.$refs[this.compRef].toggleRowSelection(row); }
                    const multipleSelection = [];
                    if (!this.multiple) {
                      if (this.selection.length > 1) {
                        const del_row = this.selection.shift();
                        this.$refs[this.compRef].toggleRowSelection(del_row, false);
                      }
                      multipleSelection.push(this.selection[0]);
                    }
                    this.selection = this.multiple ? this.selection : multipleSelection;
                    this.$emit("select", this.selection, row);
                  },
                  "row-contextmenu": (row, column, event) => {
                    this.$emit("row-contextmenu", row, column, event);
                  },
                  "row-dblclick": (row, column, event) => {
                    this.$emit("row-dblclick", row, column, event);
                  },
                  "header-click": (column, event) => {
                    this.$emit("header-click", column, event);
                  },
                  "header-contextmenu": (column, event) => {
                    this.$emit("header-contextmenu", column, event);
                  },
                  "sort-change": ({ column, prop, order }) => {
                    this.$emit("sort-change", { column, prop, order });
                  },
                  "filter-change": (filters) => {
                    this.$emit("filter-change", filters);
                  },
                  "current-change": (currentRow, oldCurrentRow) => {
                    this.$emit("current-change", currentRow, oldCurrentRow);
                  },
                  "header-dragend	": (newWidth, oldWidth, column, event) => {
                    this.$emit("header-dragend	", newWidth, oldWidth, column, event);
                  },
                  "expand-change": (row, expandObj) => {
                    this.$emit("expand-change", row, expandObj);
                  }
                }
              }}
            >
              {this.isSelectFlagMeth()}
              {this.isSequenceFlagMeth()}
              {this.columns.filter(i => i.hidden !== true).map((column) => {
                const generateChildColumn = (column) => {
                  const scopedSlots =
                    column.slot || column.render || column.component
                      ? {
                        scopedSlots: {
                          default(scope) {
                            const exportVal = {
                              column: scope.column,
                              $index: scope.$index,
                              row: scope.row,
                              default: column
                            };
                            if (column.slot) {
                              return self.$scopedSlots[column.slot](exportVal);
                            } else if (column.render) {
                              return column.render(h, exportVal, self);
                            } else if (column.component) {
                              return <column.component />;
                            }
                          }
                        }
                      }
                      : {};
                  return (
                    <el-table-column
                      key={column.prop}
                      {...{
                        attrs: {
                          "show-overflow-tooltip": !column.tooltip,
                          ...column,
                          align: column.align ? column.align : "center"
                        }
                      }}
                      {...scopedSlots}
                    >
                      {column.children &&
                        column.children.map((item) => {
                          return generateChildColumn(item);
                        })}
                    </el-table-column>
                  );
                };
                return generateChildColumn(column);
              })}
            </el-table>
            {this.generatePage()}
          </div >
        </div >
      </div >
    );
  }
};
</script>

<style lang="less" scoped>
/deep/.el-table th {
  color: #333333;
  background-color: #ebf6ff;
  text-align: center;
}

.cell-text-button {
  font-size: 14px;
  font-weight: 400;
  color: #23d9ff;
  line-height: 22px;
  cursor: pointer;
  text-align: center;
}

/deep/.el-table th.gutter {
  display: table-cell !important;
}

// /deep/.el-table__fixed {
//   &:before {
//     content: "";
//     position: absolute;
//     left: 0;
//     top: 0;
//     width: 100%;
//     background-color: white;
//     z-index: 4;
//   }
// }
/deep/.is-center .el-tooltip {
  width: 100% !important;
}

.title {
  width: 100%;
  font-family: "MicrosoftYaHeiUI-Bold", "Microsoft YaHei UI Bold", "Microsoft YaHei UI";
  font-weight: 700;
  font-style: normal;
  font-size: 28px !important;
  text-align: left;
  color: #333333;
  text-align: center;
  line-height: 35px;
}

.leftTopBtn {
  float: left;
  margin-bottom: 10px;
  display: flex;
  height: 36px;
}

li {
  list-style-type: none;
  margin-right: 10px;
}

.formLabel {
  height: 55px;
  font-size: 16px;
  color: #606266;
  margin-right: 10px;
  width: fit-content;
}

:deep(.el-input) {
  .el-input__inner {
    height: 35px;
  }
}

/* :deep(.el-select) {
  .el-input__inner {
    height: auto !important;
  }
} */

.el-textarea:deep(.el-textarea__inner) {
  resize: none;
  min-height: 35px !important;
  max-height: 100px !important;
}

:deep(.el-table__cell) {
  padding: 11px 0;
}
</style>
<style lang="less">
.el-tooltip__popper {
  max-width: 20% !important;
  word-wrap: break-word !important;
}
</style>
